package org.kwin.tomcat.servlet.http;

import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author : wangkai
 * @version V1.0
 * @Package org.kwin.tomcat.servlet.http
 * @Description:
 * @date 2021年10月12日 9:59
 **/
public class ServletOutputStream {
    private HttpServletResponse resp;
    
    public ServletOutputStream(HttpServletResponse resp) {
        this.resp = resp;
    }
    
    public void write(String content) throws IOException {
        if (content == null || content.length() == 0)
        {
            return;
        }
        write(content.getBytes("UTF-8"));
    }
    
    public void write(byte[] bytes) throws IOException {
        if (bytes == null || bytes.length == 0)
        {
            return;
        }
        try {
            // 设置 http协议及请求头信息
            FullHttpResponse response = new DefaultFullHttpResponse(
                // 设置http版本为1.1
                HttpVersion.HTTP_1_1,
                // 设置响应状态码
                HttpResponseStatus.OK,
                // 将输出值写出
                Unpooled.wrappedBuffer(bytes));
            response.headers().set("Content-Type", resp.getContentType());
            resp.getCtx().write(response);
        } finally {
            resp.getCtx().flush();
            resp.getCtx().close();
        }
    }
}
